﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace VoicePhone.Common
{
    /// <summary>  
    /// 实体类序列化的反序列化的类  
    /// </summary>  
    /// <typeparam name="T"></typeparam>  
    public abstract class EntityClassXmlSerializer<T>
    {
        /// <summary>  
        /// 实体类序列化成xml string  
        /// </summary>  
        /// <param name="entity"></param>  
        /// <returns></returns>  
        public string ToXMLString(T entity)
        {
            return XmlSerializerHelper.XmlSerialize(entity);
        }
        /// <summary>  
        /// 实体类反序列化  
        /// </summary>  
        /// <param name="xml"></param>  
        /// <returns></returns>  
        public static T ReadFromXML(string xml)
        {
            return XmlSerializerHelper.XmlDeserialize<T>(xml);
        }

        private string FormatXml(string xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            MemoryStream mstream = new MemoryStream(1024);
            XmlTextWriter writer = new XmlTextWriter(mstream, null);
            writer.Formatting = Formatting.Indented;
            doc.WriteTo(writer);
            writer.Flush();
            writer.Close();
            Encoding encoding = Encoding.GetEncoding("utf-8");
            string result = encoding.GetString(mstream.ToArray());
            mstream.Close();
            return result;
        }

        public void Save(string xmlStr, string fileName)
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config", fileName);
            File.WriteAllText(filePath, xmlStr);
        }
    }
}
